package com.citycloud.ccuap.tc.admin.projectdefaultfunction;

import com.citycloud.ccuap.commons.json.TreeNode;
import com.citycloud.ccuap.framework.exception.ApplicationException;
import com.citycloud.ccuap.framework.service.mybatis.MybatisServiceImpl;
import com.citycloud.ccuap.tc.admin.entity.SysProjectDefaultFunction;
import com.citycloud.ccuap.tc.admin.repository.SysProjectDefaultFunctionRepository;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 项目（站点）默认菜单业务处理实现
 * @author zhusr
 *
 */
@Service
public class ProjectDefaultFunctionService extends MybatisServiceImpl<SysProjectDefaultFunctionRepository, SysProjectDefaultFunction, String> implements IProjectDefaultFunctionService {

	/**
	 * 父节点下是否存在子节点
	 * 
	 * @param pid 父节点
	 * @return
	 */
	 private boolean hasChildNode(String pid) {
	 	Long count = repository.countByPid(pid);
	 	
	 	if(count == 0){
	 		return false;
	 	} else {
	 		return true;
	 	}
	 }
	 
	 /**
	 * 递归获取父节点下的所有子节点
	 * 
	 * @param pid 父节点
	 * @return
	 */
	 private List<String> getChildNodeIdList(String pid) {
	 	List<String> childNodeIdList = new ArrayList<String>();
	 	
		List<SysProjectDefaultFunction> childNodeList = repository.findByPid(pid);
		
		if(childNodeList!= null){
			for (SysProjectDefaultFunction sysPrjectDefaultFunction : childNodeList) {
				childNodeIdList.add(sysPrjectDefaultFunction.getFunId());
				
				//递归获取子节点
				childNodeIdList.addAll(getChildNodeIdList(sysPrjectDefaultFunction.getFunId()));
			}
		}
		
		return childNodeIdList;
	 }
	 
	 @Override
	 public void deleteNode(String funId) {
		List<String> childNodeIdList = getChildNodeIdList(funId);
		if (childNodeIdList.size() > 0) {
			throw new ApplicationException("您选中的菜单有子节点，不能删除！");
		}
        for(String childNodeId:childNodeIdList){
        	repository.deleteById(childNodeId);
        }
        repository.deleteById(funId);
	 }
	 
	 @Override
	 public void deleteNodeList(List<String> funIdList) {
    	for (String funId : funIdList) {
            deleteNode(funId);
        }
	 }
	 
	 @Override
	 public List<TreeNode> findNextChildNodeTree(String pid) {
	 	List<TreeNode> treeList = new ArrayList<TreeNode>();
	 	
 		List<SysProjectDefaultFunction> nodeList;
	 	if (pid == null) {
	 		nodeList = repository.findByPidNullOrderByOrderNo();
	 	} else {
	 		nodeList = repository.findByPidOrderByOrderNo(pid);
	 	}
 		if(nodeList!= null){
			for (SysProjectDefaultFunction sysPrjectDefaultFunction : nodeList) {
				TreeNode node = new TreeNode();
				node.setId(sysPrjectDefaultFunction.getFunId().toString());
				node.setText(sysPrjectDefaultFunction.getFunName());
				node.setExpanded(true);
				boolean isLeaf = !hasChildNode(sysPrjectDefaultFunction.getFunId());
				node.setLeaf(isLeaf);
				
				treeList.add(node);
			}
		}

        return treeList;
	 }

	@Override
	public void updateFullPathBatch(String funId, String existFullPath, String fullPath) {

		List<SysProjectDefaultFunction> funList = getAllChildList(funId);
		for (SysProjectDefaultFunction sysFunction : funList) {
			String path = sysFunction.getFullPath();
			if (StringUtils.isBlank(path)) {
				throw new ApplicationException("全路径为空");
			}
			sysFunction.setFullPath(path.replaceFirst(existFullPath, fullPath));
			repository.save(sysFunction);
		}

	}

	@Override
	public List<SysProjectDefaultFunction> getAllChildList(String funId) {
		List<SysProjectDefaultFunction> allChildList = new ArrayList<SysProjectDefaultFunction>();

		List<SysProjectDefaultFunction> childList = repository.findByPidOrderByOrderNo(funId);

		if (childList != null) {
			for (SysProjectDefaultFunction sysFunction : childList) {
				allChildList.add(sysFunction);

				// 递归获取子节点
				allChildList.addAll(getAllChildList(sysFunction.getFunId()));
			}
		}

		return allChildList;
	}

	@Override
	public List<TreeNode> findNodeTreeByName(String funName) {
		List<TreeNode> treeList = new ArrayList<>();
		List<SysProjectDefaultFunction> nodeList;
		
		nodeList = repository.findByFullPathContainingOrderByOrderNo(funName);

		Set<String> funSet = new HashSet<>();
		if (nodeList != null) {
			for (SysProjectDefaultFunction sysFunction : nodeList) {
				String[] pathList = sysFunction.getFullPath().split("/");
				int j = 0;
				for (int i = 0; i < pathList.length; i++) {
					String name = pathList[i];
					if (name.contains(funName)) {
						j = i + 1;
					}
				}

				for (int i = 0; i < j; i++) {
					String name = pathList[i];
					funSet.add(name);
				}

			}
		}
		Iterator<String> iterator = funSet.iterator();

		List<SysProjectDefaultFunction> todoList = new ArrayList<SysProjectDefaultFunction>();
		while (iterator.hasNext()) {
			String name = iterator.next();
			List<SysProjectDefaultFunction> funList = repository.findByFunNameOrderByOrderNo(name);	
			for (SysProjectDefaultFunction sysFunction : funList) {
				todoList.add(sysFunction);
			}
		}

		for (SysProjectDefaultFunction sysFunction : todoList) {
			if (sysFunction.getPid() == null) {
				TreeNode node = new TreeNode();
				node.setId(sysFunction.getFunId().toString());
				node.setText(sysFunction.getFunName());
				node.setExpanded(true);
				treeList.add(findChildren(node, todoList));
			}
		}
		return treeList;
	}
	
	/**
	 * 递归查找子节点
	 * 
	 * @param treeNode
	 * @param funList
	 * @return
	 */
	private TreeNode findChildren(TreeNode treeNode, List<SysProjectDefaultFunction> funList) {
		for (SysProjectDefaultFunction sysFunction : funList) {
			if (sysFunction.getPid() != null && treeNode.getId().equals(sysFunction.getPid())) {
				if (treeNode.getChildren() == null) {
					treeNode.setChildren(new ArrayList<TreeNode>());
				}
				TreeNode node = new TreeNode();
				node.setId(sysFunction.getFunId().toString());
				node.setText(sysFunction.getFunName());
				node.setExpanded(true);
				boolean isLeaf = !hasChildNode(sysFunction.getFunId());
				node.setLeaf(isLeaf);
				treeNode.getChildren().add(findChildren(node, funList));
			}
		}
		return treeNode;
	}
}